﻿using System.Net.Http.Headers;
using System.Reflection;

namespace GMS.NET.Web.Components.Shared.Global.Attributes
{
    /// <summary>
    /// 请求动态修改地址
    /// 要求存在参数 url
    /// 会默认取第一个参数
    /// </summary>
    public class ApiDynamicUrlAttribute : ApiFilterAttribute
    {
        public override Task OnRequestAsync(ApiRequestContext context)
        {
            var requestUrl = "";
            var attr = context.ActionDescriptor.Parameters
                .FirstOrDefault(x=>x.Attributes.FirstOrDefault()!
                .GetType().Name == "ApiUrlAttribute");
            if (attr is not null) requestUrl = (attr.Attributes.FirstOrDefault() as ApiUrlAttribute)!.Url;
            var options = context.HttpContext.HttpApiOptions;
            HttpApiRequestMessage requestMessage = context.HttpContext.RequestMessage;
            requestMessage.RequestUri = requestMessage.MakeRequestUri(new Uri($"{options.HttpHost!.AbsoluteUri}{requestUrl}"));
            return Task.CompletedTask;
        }

        public override Task OnResponseAsync(ApiResponseContext context)=>Task.CompletedTask;
    }

    /// <summary>
    /// 动态请求地址
    /// </summary>
    public class ApiUrlAttribute : HttpContentAttribute
    {
        public string? Url { get; set; }
        protected override Task SetHttpContentAsync(ApiParameterContext context)
        {
            try
            {
                if (context.ParameterValue is string url)
                {
                    this.Url = url;
                    return Task.CompletedTask;
                }
            }
            catch {  }
            throw new Exception("The ApiUrlAttribute feature requires the interface address as a string,For example, api/data/getdata ");
        }
    }
}
